package org.apache.ibatis.lgtest.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author lg
 * @description
 * @create 2019-09-19
 **/
public class NonBlockServer {

  public static void main(String[] args) throws IOException, InterruptedException {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.bind(new InetSocketAddress("localhost", 12345));
    serverSocketChannel.configureBlocking(false);
    SocketChannel socketChannel = null;
    System.out.println("服务端启动成功");
    while (true) {
      socketChannel = serverSocketChannel.accept();
      if(null != socketChannel && socketChannel.isConnected()){
        System.out.println("连接客户端成功：" + socketChannel.getLocalAddress().toString());
        break;
      }
      System.out.println("正在监听客户端的连接...");
      Thread.sleep(1000);
    }


    final ByteBuffer readBuffer = ByteBuffer.allocate(1024);
    ByteBuffer writeBuffer = ByteBuffer.allocate(1024);

    final SocketChannel fsoccketChannel = socketChannel;
    //开启一个线程监听客户端消息
    new Thread(() -> {
      int n = 0;

      while (n >= 0) {
        try {
          n = fsoccketChannel.read(readBuffer);
        } catch (IOException e) {
          e.printStackTrace();
        }

        System.out.println("收到客户端消息：" + new String(readBuffer.array(), 0, n));
      }
    });


    while (true) {
      writeBuffer.clear();
      BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
      String line = reader.readLine() + "\n";
      writeBuffer.put(line.getBytes());
      writeBuffer.flip();
      socketChannel.write(writeBuffer);
    }

  }
}
